from PySide6.QtCore import QThread, Signal
import serial
from .base_thread import BaseThread

class SerialThread(BaseThread):
    def __init__(self, port, baudRate):
        super().__init__()
        self.port = port
        self.baudRate = baudRate
        self.serial = None
        
    def _connect(self):
        try:
            self.serial = serial.Serial(
                port=self.port,
                baudrate=int(self.baudRate),
                timeout=3
            )
            self._is_running = True
            self.connected.emit(True)
            return True
        except Exception as e:
            self.error.emit(str(e))
            self.connected.emit(False)
            return False
    
    def _disconnect(self):
        self._is_running = False
        if self.serial:
            self.serial.close()
            self.serial = None
        self.connected.emit(False)
    
    def write(self, data):
        if self.serial and self.serial.is_open:
            try:
                print(f"发送数据: {data}")
                self.serial.write(data.encode('utf-8'))
            except Exception as e:
                self.error.emit(str(e))
    
    def is_connected(self):
        return self.serial is not None and self.serial.is_open
    
    def get_connection_info(self):
        return f"Serial - {self.port}:{self.baudRate}"
    
    def _read_data(self):
        if self.serial and self.serial.in_waiting:
            data = self.serial.read(self.serial.in_waiting).decode('utf-8', errors='ignore')
            if data:
                self.received.emit(data)